package com.mb.app.appused.views;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author wo2app
 * @date 创建时间：2015年10月8日 下午8:39:41
 * @version 1.0
 * @parameter
 * @since
 * @return
 */

public class BannerView extends FrameLayout {

	protected Context context;
	private List<View> banerImgs = new ArrayList<View>();
	private List<View> banerImgs2 = new ArrayList<View>();
	private ViewPager banner;
	private int current = 1;

	private final static int TOCHANGE = 0X001184;
	private float delayTime = 1;
	float currentTime = 0;
	private boolean isStart = true;
	BannerClickListner clickListener;
	Boolean inAction = false;
	Circle circle;

	public BannerView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.context = context;
		init();
	}

	public BannerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		this.context = context;
		init();
	}

	void init() {
		this.banner = new ViewPager(this.context);
		this.addView(banner, getFall());

		LayoutParams lp2 = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 100, Gravity.BOTTOM);
		TextView temp = new TextView(this.context);
		temp.setBackgroundColor(0x567f7f7f);
		this.addView(temp, lp2);
		temp.setText("");
		temp.setTextColor(Color.WHITE);
		temp.setTextSize(14);
		temp.setPadding(32, 0, 0, 0);
		temp.setGravity(Gravity.CENTER_VERTICAL);

		circle = new Circle(getContext());
		this.addView(circle, lp2);
		circle.align = 2;
	}

	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			inAction = true;
			break;
		case MotionEvent.ACTION_UP:
			if (inAction) {
				Click();
			}
			inAction = false;
			break;
		case MotionEvent.ACTION_OUTSIDE:
			inAction = false;
			break;
		}
		return false;
	}

	void Click() {
		if (clickListener != null) {
			int position = current - 1;
			if (current == 1)
				position = 0;
			if (current == banerImgs.size())
				position = banerImgs.size() - 1;

			clickListener.OnClick(position);
		}
	}

	/**
	 * 添加单条广告
	 * 
	 * @param view
	 */
	public void addBanner(View view) {
		this.banerImgs.add(view);
	}

	@SuppressWarnings("deprecation")
	public void addBanner(Bitmap bit) {
		ImageView img = new ImageView(context);
		img.setLayoutParams(getFall());
		Drawable drawable = new BitmapDrawable(bit);
		img.setBackgroundDrawable(drawable);
		addBanner(img);
	}

	public void addBanner(int id) {
		Resources res = getResources();
		Bitmap bmp = BitmapFactory.decodeResource(res, id);
		addBanner(bmp);
	}

	/**
	 * 确认提交
	 */
	public void commint() {
		if (!(banerImgs.size() > 0))
			return;
		if (banner == null) {
			return;
		}

		if (banerImgs.size() == 2) {
			for (int a = 0; a < 6; a++) {
				banerImgs2.add(banerImgs.get(a % banerImgs.size()));
			}
		} else {
			for (int a = 0; a < banerImgs.size(); a++) {
				if (a == 0)
					banerImgs2.add(banerImgs.get(banerImgs.size() - 1));

				banerImgs2.add(banerImgs.get(a));

				if (a == (banerImgs.size() - 1))
					banerImgs2.add(banerImgs.get(0));
			}
		}
		
		if (banerImgs.size() < 2) {
			current = 0;
			setPage(banner, banerImgs);
		} else {
			current = 1;
			setPage(banner, banerImgs2);
			// Log.e("ImageCout", banerImgs2.size() + ">>>>");
		}
		circle.setCout(banerImgs.size());
		circle.invalidate();
		start();
	}

	public void addListener(BannerClickListner clickListener) {
		this.clickListener = clickListener;
	}

	void start() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (isStart) {
					try {
						Thread.sleep((long) (delayTime * 1000));
						Message msg = new Message();
						msg.what = TOCHANGE;
						currentTime += 1;
						handler.sendMessage(msg);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case TOCHANGE:
				if (currentTime > 4 && banerImgs.size() > 1) {
					current += 1;
					currentTime = 0;
					setCurrent(current % banerImgs2.size(), banerImgs2.size());
				}
				break;
			default:
				break;
			}
		}
	};

	LayoutParams getFall() {
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		return lp;
	}

	/**
	 * 设置广告
	 * 
	 * @param pager
	 * @param views
	 */
	private void setPage(final ViewPager pager, final List<View> views) {
		if (pager == null) {
			return;
		}
		PagerAdapter mPagerAdapter = new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				return views.size();
			}

			// @Override
			public void destroyItem(View container, int position, Object object) {
				// ((ViewPager) container).removeView(views.get(position
				// % views.size()));
			}

			@Override
			public Object instantiateItem(View container, int position) {
				position = position % views.size();

				if (views.get(position).getParent() != null) {
					((ViewPager) container).removeView(views.get(position));
				}
				if (views.get(position).getParent() == null) {
					// 添加那个view到viewPager中
					((ViewPager) container).addView(views.get(position), 0);
				}

				// ((ViewPager) container).removeView(views.get(position));
				// ((ViewPager) container).addView(views.get(position));
				// return views.get(position);
				// Log.e("instanceItem", position + "----");
				return views.get(position);
			}

		};

		pager.setAdapter(mPagerAdapter);
		pager.setCurrentItem(current, false);
		// pager.setOffscreenPageLimit(views.size());
		pager.addOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				// Log.e("info", position + ">>>>" + views.size());
				current = position;
				// Log.e("info", "<--onPageSelected-->" + position);

			}

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
				// TODO Auto-generated method stub
				// if (position == 0 && positionOffset == 0)
				// banner.setCurrentItem(views.size() - 2, false);
				// else if (position == views.size() - 1 && positionOffset == 0)
				// banner.setCurrentItem(1, false);
				currentTime = 0;

			}

			@Override
			public void onPageScrollStateChanged(int state) {
				// TODO Auto-generated method stub
				// Log.e("info", "<--onPageScrollStateChanged-->" + state);
				if (banerImgs.size() < 2)
					return;

				if (current == 0 && state == 0) {
					banner.setCurrentItem(views.size() - 2, false);
				}
				if (current == views.size() - 1 && state == 0) {
					banner.setCurrentItem(1, false);
				}

				if (state == 0) {
					circle.setCurrent(getPostion(current) % banerImgs.size());
					circle.invalidate();
				}
			}
		});
	}

	int getPostion(int temp) {
		int position = temp - 1;
		if (temp == 1)
			position = 0;
		if (temp == banerImgs.size())
			position = banerImgs.size() - 1;
		return position;
	}

	void setCurrent(int current, int max) {
		if (banerImgs.size() < 2)
			return;
		banner.setCurrentItem(current % max, true);
	}

	public interface BannerClickListner {
		public void OnClick(int position);
	}

	/**
	 * 圆点
	 * 
	 * @author xhwwz
	 * 
	 */
	class Circle extends View {

		public int cout = 0;
		public int current = 0;
		public float offset = 0;
		int align = 0; // 默认中间对齐
		Paint paint;
		Paint bgPaint;
		int radius = 18; // 内圆半径
		float distance = 60;// 距离

		public Circle(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
			init(context);
		}

		public Circle(Context context, AttributeSet attrs) {
			super(context, attrs);
			// TODO Auto-generated constructor stub
			init(context);
		}

		public Circle(Context context, AttributeSet attrs, int defStyleAttr) {
			super(context, attrs, defStyleAttr);
			// TODO Auto-generated constructor stub
			init(context);
		}

		@Override
		protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
			// TODO Auto-generated method stub
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}

		public int getCout() {
			return cout;
		}

		public void setCout(int cout) {
			this.cout = cout;
		}

		public int getCurrent() {
			return current;
		}

		public float getOffset() {
			return offset;
		}

		/**
		 * 初始化内容
		 * 
		 * @param context
		 */
		@SuppressWarnings("deprecation")
		private void init(Context context) {

			paint = new Paint();
			paint.setAntiAlias(true);
			paint.setColor(0X77ffffff);
			paint.setStyle(Paint.Style.FILL);

			bgPaint = new Paint();
			bgPaint.setAntiAlias(true);
			bgPaint.setColor(0xaaffffff);
			bgPaint.setStrokeWidth(5);
			bgPaint.setStyle(Paint.Style.STROKE);

		}

		public void setCurrent(int current) {
			this.current = current;
		}

		public void setOffset(float value) {
			this.offset = value;
		}

		@Override
		protected void onDraw(Canvas canvas) {
			// TODO Auto-generated method stub
			super.onDraw(canvas);
			float centerX = getWidth() / 2;
			float centerY = getHeight() / 2;

			if (align == 1) { // 左
				centerX = 16 + radius + distance * cout * 0.5f;
			}
			if (align == 2) { // 右
				centerX = getWidth() - (distance * cout * 0.5f) - radius - 16;
			}
			float start = centerX - distance * cout * 0.5f;
			for (int a = 0; a < cout; a++) {
				canvas.drawCircle(start + distance * a, centerY, radius, this.bgPaint);
			}
			canvas.drawCircle(start + distance * current + distance * offset, centerY, radius, paint);

		}

		public int dip2px(Context context, float dpValue) {
			final float scale = context.getResources().getDisplayMetrics().density;
			return (int) (dpValue * scale + 0.5f);
		}

	}

	public static class BannerItem {
		public String url;
		public String title;
		public int loaddImage = -1;

	}
}
